'use strict';

var fs = require('fs'),
    path = require('path');

var DATA_PATH = path.resolve(__dirname, '../../data'),
    formatDate = require('../helpers/format-date');

function getLatestDataPath() {
    var files = fs.readdirSync(DATA_PATH);
    var lastDate = files.filter(function(name) {
        return /[\d\-]+\.json/.test(name);
    }).sort(function(a, b) {
        return a >= b ? 1 : -1;
    }).reverse()[0];

    return path.join(DATA_PATH, lastDate);
}

function filterCategories(data) {
    var list = [],
        filter = [];
    Object.keys(data).forEach(function(key) {
        var category = data[key].category;
        if (list.lastIndexOf(category) === -1) {
            list.push(category);

            var parent = category.split('.')[0];

            if (filter.lastIndexOf(parent) === -1) {
                filter.push(parent);
            }
        }
    });

    list = list.sort();
    filter = filter.sort();

    return {
        list: list,
        filter: filter
    };
}

function filterEvents(data) {
    var result = [];
    Object.keys(data).forEach(function(key) {
        var event = data[key].event;
        if (result.lastIndexOf(event) === -1) {
            result.push(event);
        }
    });

    return result.sort().reverse();
}

function getLatestData() {
    var data = fs.readFileSync(getLatestDataPath());
    return JSON.parse(data);
    //return require(getLatestDataPath());
}

function save(data) {
    var newData = path.join(DATA_PATH, formatDate(new Date()) + '.json' );
    require('fs').writeFileSync(newData, JSON.stringify(data, null, 4));
}

function LineData(body, lastLineData) {
    this.currency = 'CNY';
    this.date = formatDate(body.date);
    this.category = body.category;
    this.event = body.event;
    this.note = body.note;
    this.money = parseInt(body.money, 10);
    this.order = 1;

    if (lastLineData.date === this.date) {
        this.order = lastLineData.order + 1;
    }
}

module.exports = {
    getLatestData: getLatestData,
    insert: function(body) {
        var latestData = getLatestData(),
            newLineData = new LineData(body, latestData[0]);
        latestData.unshift(newLineData);
        save(latestData);
        return newLineData;
    },
    getLatestInfo: function(limit) {
        var data = getLatestData(),
            info = {
                categories: filterCategories(data),
                events: filterEvents(data)
            };

        data = data.slice(0, limit);
        return {
            data: data,
            info: info
        };
    }
};
